package com.letv.whatslive.mongo.dao;

import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.FeedBack;
import com.letv.whatslive.model.convert.FeedBackConvert;
import com.letv.whatslive.mongo.BaseDAO;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.DBRef;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * Created by gaoshan on 15-8-31.
 */
@Repository
public class FeedBackDAO extends BaseDAO {
    private final static Logger logger = LoggerFactory.getLogger(FeedBackDAO.class);

    protected String collectionName = "feedback";

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }
    /**
     * 根据id查询
     * @param id
     * @return
     */
    public FeedBack getFeedBackById(Long id){
        DBObject dbObject = new BasicDBObject();
        dbObject.put("_id", id);
        DBObject result = dbCollection.findOne(dbObject);
        if (result == null) {
            return null;
        }
        FeedBack feedBack= FeedBackConvert.castDBObjectToFeedBack(result);
        return feedBack;
    }

    /**
     * 添加
     * @param feedBack
     * @return
     */
    public Long insertFeedBack(FeedBack feedBack){
        DBObject obj = FeedBackConvert.castFeedBackToDBObject(feedBack);
        DBRef userRef = new DBRef("user",feedBack.getUserId());
        obj.put("user",userRef);
        return this.insert(obj);
    }

    /**
     * 更新
     * @param feedBack
     */
    public void updateFeedBack(FeedBack feedBack){
        DBObject queryCondition = new BasicDBObject();
        queryCondition.put("_id", feedBack.getId());
        BasicDBObject setValue = (BasicDBObject)FeedBackConvert.castFeedBackToDBObject(feedBack);
        //剔除主键修改
        if (setValue.containsField("_id")) {
            setValue.removeField("_id");
        }
        DBRef userRef = new DBRef(this.dbCollection.getDB(),"user",feedBack.getUserId());
        setValue.put("user",userRef);
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }

    /**
     * 查询记录数
     * @param params
     * @return
     */
    public Long countFeedBackByParams(Map params){
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    /**
     * 查询
     * @param orders
     * @param params
     * @param start
     * @param limit
     * @return
     */
    public List<FeedBack> getFeedBackListByParams(Map<String, Object> orders, Map<String, Object> params, Integer start, Integer limit) {

        List<FeedBack> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip)
                    .sort(order).limit(limit);//按照视频类型和创建时间倒序
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                FeedBack program = FeedBackConvert.castDBObjectToFeedBack(dbObject);
                result.add(program);
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        return result;
    }

    /**
     * 删除
     * @param userid
     */
    public void deleteProgram(Long userid){
        BasicDBObject query = new BasicDBObject();
        query.put("_id",userid );
        this.dbCollection.remove(query);
    }

    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照创建时间排序
            order.append("createTime", -1);
        }
        return order;
    }


    private BasicDBObject getBasicDBObjectByParams(Map params){
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("id") != null) {
                query.put("_id", ObjectUtils.toLong(params.get("id")));
            }
            if(params.get("programId")!=null){
                query.put("programId", ObjectUtils.toString(params.get("programId")));
            }
            if (params.get("userId") != null) {
                query.put("userId", ObjectUtils.toLong(params.get("userId")));
            }
            if(params.get("imei")!=null){
                query.put("imei",ObjectUtils.toString(params.get("imei")));
            }
            if(params.get("phone")!=null){
                query.put("phone",ObjectUtils.toString(params.get("phone")));
            }
            if(params.get("feedBack")!=null){
                query.put("feedBack",ObjectUtils.toString(params.get("feedBack")));
            }
            if (params.get("lastGetPlayUrlTime") != null) {
                query.put("lastGetPlayUrlTime", ObjectUtils.toLong(params.get("lastGetPlayUrlTime")));
            }
            if (params.get("lastPlayTime") != null) {
                query.put("lastPlayTime", ObjectUtils.toLong(params.get("lastPlayTime")));
            }
            if (params.get("lastTotalPlayTime") != null) {
                query.put("lastTotalPlayTime", ObjectUtils.toLong(params.get("lastTotalPlayTime")));
            }
            if(params.get("ip")!=null){
                query.put("ip",ObjectUtils.toString(params.get("ip")));
            }
            if(params.get("network")!=null){
                query.put("network",ObjectUtils.toString(params.get("network")));
            }
            if(params.get("startTime_start") != null && params.get("startTime_end") != null){
                query.put("createTime", new BasicDBObject("$gt",
                        ObjectUtils.toLong(params.get("startTime_start"))).append("$lte", ObjectUtils.toLong(params.get("startTime_end"))));

            }
        }
        return query;
    }
}
